<template>
  <div style="width: 50%; margin: 0 auto" class="card">
    <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px" style="padding: 20px">
      <el-form-item prop="practiceLicense" label="认证证件">
        <el-upload
          :action="baseUrl + '/files/upload'"
          :on-success="handleFileUpload"
          :show-file-list="false"
          class="avatar-uploader"
        >
          <img v-if="data.form.practiceLicense" :src="data.form.practiceLicense" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item prop="principalName" label="姓名">
        <el-input v-model="data.form.principalName" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item prop="principalNo" label="身份证号">
        <el-input v-model="data.form.principalNo" placeholder="请输入身份证号"></el-input>
      </el-form-item>
      <el-form-item prop="status" label="审核状态">
        <el-tag type="warning" v-if="data.form.status === '待提交'">待提交</el-tag>
        <el-tag type="info" v-if="data.form.status === '待审核'">待审核</el-tag>
        <el-tag type="danger" v-if="data.form.status === '审核拒绝'">审核拒绝</el-tag>
        <el-tag type="success" v-if="data.form.status === '审核通过'">审核通过</el-tag>
      </el-form-item>
      <div style="text-align: center">
        <el-button type="primary" @click="handleUpdate" :disabled="data.user.status !== '待提交' && data.user.status !== '审核拒绝'">提 交</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
  import {reactive, ref} from 'vue'
  import request from '@/utils/request.js'
  import {ElMessage, ElMessageBox} from 'element-plus'

  const baseUrl = import.meta.env.VITE_BASE_URL

  const formRef = ref()

  // 身份证校验函数
  const validateIDCard = (rule, value, callback) => {
    if (!value) return callback()
    const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    if (!reg.test(value)) {
      callback(new Error('身份证号格式不正确'))
    } else {
      // 校验出生日期（简单版本）
      const len = value.length
      if (len === 18) {
        const birth = value.substr(6, 8)
        const year = birth.substr(0, 4)
        const month = birth.substr(4, 2)
        const day = birth.substr(6, 2)
        const date = new Date(year + '-' + month + '-' + day)
        if (isNaN(date)) {
          callback(new Error('身份证出生日期无效'))
          return
        }
      }
      callback()
    }
  }

  const data = reactive({
    user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
    form: {},
    rules: {
      practiceLicense: [
        { required: true, message: '请上传经营许可证', trigger: 'change' }
      ],
      principalName: [
        { required: true, message: '姓名不能为空', trigger: ['blur', 'change']}
      ],
      principalNo: [
        { required: true, message: '身份证号不能为空', trigger: 'blur' },
        { validator: validateIDCard, trigger: ['blur', 'change'] }
      ]
    }
  })

  const load = () => {
    request.get('/petShop/query?id=' + data.user.id).then(res => {
      if (res.code === '200') {
        data.form = res.data
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  load()

  const handleFileUpload = (res) => {
    data.form.practiceLicense = res.data
  }

  const handleUpdate = () => {
    formRef.value.validate(validate => {
      if (validate) {
        ElMessageBox.confirm('您确定提交审核吗?', '确认', { type: 'warning' }).then(res => {
          request.put('/petShop/identify/submit', {
            id: data.form.id,
            practiceLicense: data.form.practiceLicense,
            principalName: data.form.principalName,
            principalNo: data.form.principalNo
          }).then(res => {
            if (res.code === '200') {
              load()
              ElMessage.success('提交成功，等待管理员审核')
            } else {
              ElMessage.error(res.msg)
            }
          })
        }).catch()
      }
    })
  }

</script>

<style scoped>
.avatar-uploader {
  height: 120px;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>